package com.wy.pdf_test;

import jakarta.annotation.PostConstruct;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;

@RestController
public class PdfRenderController {

    private Path tempHtmlPath;

    @PostConstruct
    public void init() throws IOException {
        // 将 classpath 中的 HTML 复制到临时目录
        InputStream htmlInputStream = getClass().getClassLoader().getResourceAsStream("templates/examReport.html");
        if (htmlInputStream == null) {
            throw new FileNotFoundException("未找到 examReport.html 文件！");
        }

        File tempHtmlFile = File.createTempFile("examReport-", ".html");
        FileCopyUtils.copy(htmlInputStream, new FileOutputStream(tempHtmlFile));
        this.tempHtmlPath = tempHtmlFile.toPath();
    }

    @GetMapping("/gen-pdf1")
    public ResponseEntity<Resource> generatePdf() throws IOException {
        // 创建唯一 PDF 文件名
        String pdfFileName = "rendered-" + UUID.randomUUID() + ".pdf";
        Path pdfOutputPath = Files.createTempFile("rendered-", ".pdf");

        // 渲染 HTML 为 PDF
        HtmlToPdfRenderer.render("file:///" + tempHtmlPath.toAbsolutePath().toString(), pdfOutputPath.toAbsolutePath().toString());

        // 等待渲染完成（简单轮询 5~10 秒）
        int waitSec = 0;
        while (!Files.exists(pdfOutputPath) && waitSec < 10) {
            try {
                Thread.sleep(1000);
                waitSec++;
            } catch (InterruptedException ignored) {}
        }

        if (!Files.exists(pdfOutputPath)) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }

        // 返回 PDF 文件
        InputStreamResource resource = new InputStreamResource(new FileInputStream(pdfOutputPath.toFile()));
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + pdfFileName)
                .contentType(MediaType.APPLICATION_PDF)
                .contentLength(Files.size(pdfOutputPath))
                .body(resource);
    }
}
